﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using log4net;
using Mate.Core;
using Mate.Core.Base;
using Mate.Db.Model.Users;
using Mate.Dto.Users;
using Mate.Framework.Authentication;
using Mate.Framework.Extensions;
using Mate.Framework.Helper;
using Mate.User.Service;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Mate.Admin.Controllers
{
    public class LoginController : Controller
    {

        private readonly IAdminUserService _adminUserService;
        private readonly ILog log;
        public LoginController(AdminUserService adminUserService, ILog log)
        {
            this.log = log;
            this._adminUserService = adminUserService;
        }

        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }

        #region 登录
        [HttpPost]
        public IActionResult Index(LoginModel model)
        {
            var result = new BaseResult();
            if (string.IsNullOrWhiteSpace(model.ValidateCode))
            {
                result.ResultCode = ResultCode.ParamError;
                result.Message = "请输入验证码";
                return Json(result);
            }
            var sessionCode = HttpContext.Session.GetString(Consts.AdminLoginValidateCodeKey);
            if (sessionCode.ToLower() != model.ValidateCode.Trim().ToLower())
            {
                result.ResultCode = ResultCode.ParamError;
                result.Message = "验证码错误";
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(model.UserNo))
            {
                result.ResultCode = ResultCode.ParamError;
                result.Message = "账号不能为空";
                return Json(result);
            }
            
            if (string.IsNullOrWhiteSpace(model.Password))
            {
                result.ResultCode = ResultCode.ParamError;
                result.Message = "密码不能为空";
                return Json(result);
            }

            var adminUser = _adminUserService.GetByUserNameAndPwd(model.UserNo, EncryptUtil.MD5Encrypt16(model.Password));
            if (adminUser == null)
            {
                result.ResultCode = ResultCode.Fail;
                result.Message = "账号或密码错误";
                return Json(result);
            }

            if (!adminUser.is_enable)
            {
                result.ResultCode = ResultCode.Fail;
                result.Message = "该用户被禁用";
                return Json(result);
            }

            //登录认证
            SignInAsync(adminUser);

            result.ResultCode = ResultCode.Success;
            result.Message = "登录成功";
            return Json(result);
        }
        #endregion

        #region 登录认证
        private void SignInAsync(admin_user adminUser)
        {
            #region 登录认证
            var claims = new List<Claim> {
                        new Claim("UserName", adminUser.user_name,ClaimValueTypes.String),
                        new Claim("UserNo", adminUser.user_no,ClaimValueTypes.String),
                        new Claim("Id", adminUser.id.ToString(),ClaimValueTypes.String),
                        new Claim("RoleId", adminUser.roles_id.ToString(),ClaimValueTypes.String),
                    };
            var userIdentity = new ClaimsIdentity(claims, "AdminUser");
            var userPrincipal = new ClaimsPrincipal(userIdentity);

            HttpContext.SignInAsync(AuthenticationDefaults.AuthenticationScheme, userPrincipal,
              new AuthenticationProperties
              {
                  ExpiresUtc = DateTime.UtcNow.AddDays(10),
                  IsPersistent = true,
                  AllowRefresh = false
              });
            #endregion

            //登录成功更新最后登录时间
            _adminUserService.UpdateLastLoginTime(adminUser.id);
        }
        #endregion

        #region 验证码
        /// <summary>
        /// 验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult CreateValidateCode()
        {
            VierificationCodeHelper vCode = new VierificationCodeHelper();
            string code = "";
            MemoryStream ms = vCode.Create(out code);
            HttpContext.Session.SetString(Consts.AdminLoginValidateCodeKey, code);
            Response.Body.Dispose();
            return File(ms.ToArray(), @"image/png");
        }
        #endregion

        #region 注销
        public IActionResult Logout()
        {
            HttpContext.SignOutAsync(AuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("Index");
        }
        #endregion
    }
}